package term

import (
	"context"
	"time"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetTermByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetTermByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTermByIdLogic {
	return &GetTermByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetTermByIdLogic) GetTermById(req *types.IDReq) (*types.ForumTermInfoResp, error) {
	if req.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	data, err := l.svcCtx.ForumRpc.BackendGetTermById(l.ctx, &forumclient.TermIdReq{
		Id:        req.Id,
		WithMeta:  pointy.GetPointer(uint32(1)),
		WithMedia: pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return nil, err
	}

	var meta []*types.MetaInfo
	if len(data.Meta) > 0 {
		for _, v := range data.Meta {
			meta = append(meta, &types.MetaInfo{
				Id:    v.Id,
				Key:   v.Key,
				Value: v.Value,
			})
		}
	}

	var media []*types.MediaInfo
	if len(data.Media) > 0 {
		for _, v := range data.Media {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			filename, mimeType, metaData := utils.ParseMetaData(v.MetaData)
			media = append(media, &types.MediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Thumbnail: v.Thumbnail,
				Order:     v.Order,
				Url:       pointy.GetPointer(url),
				Name:      pointy.GetPointer(filename),
				MimeType:  pointy.GetPointer(mimeType),
				AltText:   v.AltText,
				MetaData:  pointy.GetPointer(metaData),
			})
		}
	}

	option := utils.GetOptionByStatus(data.Status)

	return &types.ForumTermInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.ForumTermInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Name:     data.Name,
			Slug:     data.Slug,
			Taxonomy: data.Taxonomy,
			ParentId: data.ParentId,
			GroupId:  data.GroupId,
			DescHtml: data.Desc,
			Desc:     data.FilteredDesc,
			Sort:     data.Sort,
			Status:   data.Status,
			Count:    data.Count,
			Loaded:   pointy.GetPointer(modelx.FormatTime(time.Now(), "")),
			Meta:     meta,
			Media:    media,
		},
	}, nil
}
